package org.light.generator;

import java.util.ArrayList;
import java.util.List;

import org.light.domain.Domain;
import org.light.utils.PgsqlReflector;
import org.light.utils.StringUtil;

public class PgsqlDBDefinitionGenerator extends DBDefinitionGenerator{

	public String generateDBSql(boolean createDB,boolean commentOn, String exportStr) throws Exception{
		List<String> exports = new ArrayList<>();
		String [] exportArr = exportStr.split(",");
		for (String str :exportArr) {
			exports.add(str);
		}
		
		// set up the database;
		StringBuilder sb = new StringBuilder();
		if (createDB == true){
			sb.append("drop database if exists ").append(this.getDbName()).append(";\n");
			sb.append("create database ").append(this.getDbName()).append(";\n");
			sb.append("\\c ").append(this.getDbName()).append("\n\n");
		}
			
		for (int i=0; i < this.getDomains().size();i++){
			Domain domain = this.getDomains().get(i);
			if (StringUtil.isBlank(exportStr)||exports.contains(domain.getStandardName())) {
				if (!(domain instanceof org.light.domain.Enum)) {
					if (commentOn == false) {
						sb.append(PgsqlReflector.generateTableDefinition(domain)).append("\n");
					}else {
						sb.append(PgsqlReflector.generateTableDefinitionWithComment(domain)).append("\n");
					}
				}
			}
		}
		return sb.toString();
	}
	
	public String generateDBSql(boolean commentOn, String exportStr) throws Exception{
		return generateDBSql(false, commentOn,exportStr);
	}

	@Override
	public String generateDropTableSqls(boolean createNew, String exportStr) throws Exception {
		StringBuilder sb = new StringBuilder();
		for (int i=0; i < this.getDomains().size();i++){
			Domain domain = this.getDomains().get(i);
			if (!(domain instanceof org.light.domain.Enum)) {
				sb.append(PgsqlReflector.generatePgsqlDropTableStatement(domain)).append("\n");
			}
		}
		sb.append("\n");
		return sb.toString();
	}
	
}
